﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LERP.Domain;
using LERP.Domain.Enums;
using LERP.Web.Controllers.ViewModels.GoodsViewModels;
using Sharp.Framework;
using Sharp.Framework.Extensions;
using Sharp.Framework.Queries;
using SharpArch.NHibernate.Web.Mvc;

namespace LERP.Web.Controllers
{
    public class GoodsController : Controller
    {

        private readonly IQuery _query;

        public GoodsController(IQuery query)
        {
            this._query = query;
        }

        /// <summary>
        /// 发货货品选择
        /// </summary>
        /// <param name="id"></param>
        /// <param name="categoryId"></param>
        /// <param name="keyword"></param>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public ActionResult Select(int? id, int? categoryId, string keyword, int page = 1, int size = 10)
        {
            ViewBag.GoodsCategorys = GoodsCategorys();
            var query = _query.FindAll<Goods>().Where(m => m.Status == DataStatus.Normal);
            if (categoryId.HasValue)
            {
                query = query.Where(m => m.Category.Id == categoryId.Value);
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(m => m.Name.Contains(keyword));
            }
            var model = query.OrderByDescending(m => m.Modified).Select(m => new GoodsSelectViewModel
                                                                                 {
                                                                                     Id = m.Id,
                                                                                     Name = m.Name,
                                                                                     CategoryName =
                                                                                         ((null == m.Category)
                                                                                              ? string.Empty
                                                                                              : m.Category.
                                                                                                    DictionaryText),
                                                                                     Gencod = m.Gencod,
                                                                                     Num = m.Num,
                                                                                     Price = m.Price,
                                                                                     Unit = m.SellUnit,
                                                                                     Volume = m.Volume

                                                                                 }).ToPagedList(page, size);
            if (id.HasValue)
            {
                var customer = _query.Get<Customer>(id.Value);
                if (null != customer)
                {
                    var ids = new List<int> { id.Value };
                    var parentid = 0; 
                    if (null != customer.Parent)
                    { 
                        parentid = customer.Parent.Id;
                        ids.Add(customer.Parent.Id);
                    }
                    if (null != customer.Parent && null != customer.Parent.Parent)
                    { 
                        ids.Add(customer.Parent.Parent.Id);
                    }
                    var list = _query.FindAll<GoodsPrice>().Where(x => ids.Contains(x.Customer.Id)).Select(x => new
                    {
                        GoodsId = x.Goods.Id,
                        CustomerId = x.Customer.Id,
                        x.Price,
                        Level = (x.Customer.Id == id ? 1 : (x.Customer.Id == parentid ? 2 : 3))
                    }).ToList();
                    foreach (var goods in model)
                    {
                        if (list.Any(x => x.GoodsId == goods.Id))
                        {
                            var customerGoods = list.Where(x => x.GoodsId == goods.Id).OrderBy(x => x.Level).FirstOrDefault();
                            if (customerGoods != null)
                            {
                                goods.Price = customerGoods.Price; 
                            }
                        }
                    }
                }
            }
            return View(model);
        }

        /// <summary>
        /// 获取货品列表
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="keyword"></param>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index(int? categoryId, string keyword, int page = 1, int size = 12)
        {
            ViewBag.GoodsCategorys = GoodsCategorys();
            var query = _query.FindAll<Goods>().Where(m => m.Status == DataStatus.Normal);
            if (categoryId.HasValue)
            {
                query = query.Where(m => m.Category.Id == categoryId.Value);
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(m => m.Name.Contains(keyword));
            }
            var model = query.OrderByDescending(m => m.Modified).Select(m => new GoodsSelectViewModel
            {
                Id = m.Id,
                Name = m.Name,
                CategoryName =
                    ((null == m.Category)
                         ? string.Empty
                         : m.Category.
                               DictionaryText),
                Gencod = m.Gencod,
                Num = m.Num,
                Price = m.Price,
                Unit = m.SellUnit,
                Volume = m.Volume

            }).ToPagedList(page, size);

            return View(model);
        }

        /// <summary>
        /// 货品详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
          [HttpGet]
        public ActionResult Details(int id)
        {
            var model = _query.Get<Goods>(id);
            if (null == model)
            {
                return View("NoFound");
            }
            return View(model);
        }

        /// <summary>
        /// 创建货品
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Create()
        {
            
            ViewBag.GoodsCategory =  GoodsCategorys();

            return View(new CreateGoodsViveModel
                            {
                                Num = 12,
                                Volume =new decimal(0.5),
                                PackageWeight = new decimal(10),
                                Price = new decimal(100)
                            });
        }
        /// <summary>
        /// 获取货品分类列表
        /// </summary>
        /// <returns></returns>
        private List<SelectListItem> GoodsCategorys()
        {
            var list = _query.FindAll<GoodsCategory>().Where(m => m.Stauts == DataStatus.Normal).Where(m=>m.Parent!=null);
            return list.OrderBy(m=>m.Parent.Id).Select(x => new SelectListItem { Text =string.Format("{0}--{1}", x.Parent.DictionaryText, x.DictionaryText), Value = x.Id.ToString() }).ToList();
        }

        /// <summary>
        /// 提交 新增货品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Transaction]
        [HttpPost]
        public ActionResult Create(CreateGoodsViveModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var entity = new Goods
                        {
                            Name = model.Name,
                            Gencod = model.Gencod,
                            Unit = model.Unit,
                            SellUnit = model.SellUnit,
                            Price = model.Price,
                            Num = model.Num,
                            Volume = model.Volume,
                            PackageWeight = model.PackageWeight,
                            Remark = model.Remark,
                            Status = DataStatus.Normal,
                            Created = DateTime.Now,
                            Modified = DateTime.Now
                        };

                    var  goodsCategory = _query.Get<GoodsCategory>(model.CategoryId); 
                    entity.Category = goodsCategory; 
                    _query.Save(entity);
                    return RedirectToAction("Index", "Goods");
                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }

            ViewBag.GoodsCategory = GoodsCategorys();
            return View(model);
        }

       /// <summary>
       /// 修改货品
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
        public ActionResult Edit(int id)
        {
            var model = _query.Get<Goods>(id);
            if (null == model)
            {
                return View("NoFound");
            }
           var goods = new CreateGoodsViveModel
               {
                   Id = model.Id,
                   CategoryId =  model.Category.Id,
                   Created = model.Created,
                   Gencod = model.Gencod,
                   Name = model.Name, 
                   Unit = model.Unit,
                   SellUnit = model.SellUnit,
                   Price = model.Price,
                   Num = model.Num,
                   Volume = model.Volume,
                   PackageWeight = model.PackageWeight,
                   Remark = model.Remark,
                   Modified = model.Modified,
                   Status =(int) model.Status
               };
           ViewBag.GoodsCategory = GoodsCategorys();
           return View(goods); 
        }

        /// <summary>
        /// 修改货品 提交
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpPost]
        [Transaction]
        public ActionResult Edit(int id, CreateGoodsViveModel model, string returnUrl)
        {
            try
            {

                if (ModelState.IsValid)
                {

                    var entity = _query.Get<Goods>(id);
                    if (null == entity)
                    {
                        return View("NoFound");
                    }
                    var goodsCategory = _query.Get<GoodsCategory>(model.CategoryId);
                    entity.Category = goodsCategory;
                    entity.Name = model.Name;
                    entity.Gencod = model.Gencod;
                    entity.Unit = model.Unit;
                    entity.SellUnit = model.SellUnit;
                    entity.Price = model.Price;
                    entity.Num = model.Num;
                    entity.Volume = model.Volume;
                    entity.PackageWeight = model.PackageWeight;
                    entity.Remark = model.Remark; 
                    entity.Modified = DateTime.Now;
                   

                    _query.Save(entity); 
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return RedirectToAction("Index");
                    }
                    return Redirect(returnUrl);

                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }

            ViewBag.GoodsCategory = GoodsCategorys();
            return View();
        }

        [Transaction]
        [HttpGet]
        public ActionResult Delete(int id, string returnUrl)
        {
            var entity = _query.Get<Goods>(id);

            if (null == entity)
            {
                return View("NoFound");
            } 
            entity.Status= DataStatus.Deleted;
            _query.Save(entity);
            if (string.IsNullOrEmpty(returnUrl))
            {
                return RedirectToAction("Index");
            }
            return Redirect(returnUrl);
        }
    }
}
